// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    // 获取文章ID
    const { id } = event
    
    if (!id) {
      return {
        success: false,
        message: '文章ID不能为空'
      }
    }
    
    // 查询文章详情
    const articleRes = await db.collection('articles').doc(id).get()
    
    if (!articleRes || !articleRes.data) {
      return {
        success: false,
        message: '文章不存在或已删除'
      }
    }
    
    const article = articleRes.data
    
    // 查询用户是否已收藏该文章
    let isCollected = false
    
    if (openid) {
      const collectionRes = await db.collection('collections')
        .where({
          _openid: openid,
          articleId: id
        })
        .count()
      
      isCollected = collectionRes.total > 0
    }
    
    // 更新文章阅读量
    await db.collection('articles').doc(id).update({
      data: {
        readCount: _.inc(1)
      }
    })
    
    return {
      success: true,
      data: {
        article,
        isCollected
      }
    }
  } catch (err) {
    console.error('获取文章详情失败', err)
    return {
      success: false,
      message: '获取文章详情失败',
      error: err
    }
  }
}